package leetcode.剑指offer.剑指II;

import leetcode.util.CommonUtils;
import leetcode.剑指offer.pojo.ListNode;
import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/8/7 17:05
 * @description：https://leetcode-cn.com/problems/SLwz0R/
 */
public class 剑指_II_21_删除链表的倒数第n个结点 {

    @Test
    public void test() {
        Solution solution = new Solution();
        ListNode head = solution.removeNthFromEnd(new ListNode(1,
                new ListNode(2,
                        new ListNode(3,
                                new ListNode(4,
                                        new ListNode(5))))), 2);
        CommonUtils.list_listNode(head);
    }

    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode A = head, B = head;
            while (n > 0) {
                A = A.next;
                n--;
                if (A == null) return head.next;
            }
            while (A.next != null) {
                A = A.next;
                B = B.next;
            }
            if (B.next != null) {
                B.next = B.next.next;
            }
            return head;
        }
    }
}
